<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\dealer;

use app\api\model\dealer\User as DealerUserModel;
use app\api\service\User as UserService;
use app\common\model\dealer\Withdraw as WithdrawModel;
use app\common\enum\dealer\withdraw\PayType as PayTypeEnum;
use app\common\enum\dealer\withdraw\ApplyStatus as ApplyStatusEnum;
use cores\exception\BaseException;

/**
 * 分销商提现明细模型
 * Class Withdraw
 * @package app\api\model\dealer
 */
class Withdraw extends WithdrawModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'store_id',
        'create_time',
        'update_time',
    ];

    /**
     * 获取分销商提现明细
     * @param int $applyStatus 申请状态
     * @return \think\Paginator
     * @throws BaseException
     * @throws \think\db\exception\DbException
     */
    public function getList(int $applyStatus = -1): \think\Paginator
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 构建查询对象
        $query = $this->getNewQuery();
        $applyStatus > -1 && $query->where('apply_status', '=', $applyStatus);
        // 查询列表数据
        return $query->where('user_id', '=', $userId)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    /**
     * 提交申请
     * @param DealerUserModel $dealer
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function submit(DealerUserModel $dealer, array $data): bool
    {
        // 数据验证
        if (!$this->validation($dealer, $data)) {
            return false;
        }
        // 事务处理
        $this->transaction(function () use ($dealer, $data) {
            // 新增申请记录
            $this->save(array_merge($data, [
                'user_id' => (int)$dealer['user_id'],
                'apply_status' => ApplyStatusEnum::WAIT,
                'platform' => getPlatform(),
                'store_id' => self::$storeId
            ]));
            // 冻结用户资金
            DealerUserModel::freezeMoney((int)$dealer['user_id'], (string)$data['money']);
        });
        return true;
    }

    /**
     * 数据验证
     * @param DealerUserModel $dealer
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function validation(DealerUserModel $dealer, array $data): bool
    {
        // 结算设置
        $settlement = Setting::getItem('settlement');
        // 最低提现佣金
        if (!is_numeric($data['money']) || $data['money'] <= 0) {
            $this->error = '提现金额不正确';
            return false;
        }
        if ($dealer['money'] <= 0) {
            $this->error = '当前用户没有可提现佣金';
            return false;
        }
        if ($data['money'] > $dealer['money']) {
            $this->error = '提现金额不能大于可提现佣金';
            return false;
        }
        if ($data['money'] < $settlement['min_money']) {
            $this->error = '最低提现金额为' . $settlement['min_money'];
            return false;
        }
        if (!in_array($data['pay_type'], $settlement['pay_type'])) {
            $this->error = '提现方式不正确';
            return false;
        }
        if ($data['pay_type'] == PayTypeEnum::ALIPAY) {
            if (empty($data['alipay_name']) || empty($data['alipay_account'])) {
                $this->error = '请补全提现信息';
                return false;
            }
        } elseif ($data['pay_type'] == PayTypeEnum::BANK_CARD) {
            if (empty($data['bank_name']) || empty($data['bank_account']) || empty($data['bank_card'])) {
                $this->error = '请补全提现信息';
                return false;
            }
        }
        return true;
    }
}
